package com.unis.controller.system;

import java.util.HashMap;
import java.util.List;

import com.unis.common.exception.app.AppRuntimeException;
import com.unis.common.secure.authc.UserInfo;
import com.unis.logger.TargetLogger;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;

import com.unis.dto.ResultDto;
import com.unis.common.exception.http.RequestEntityTooLargeException;
import com.unis.common.excel.ExportBeanExcel;
import com.unis.common.util.ValidateUtil;

import com.unis.controller.BaseController;
import com.unis.model.system.DwDzz;
import com.unis.service.system.DwDzzService;

/**
 * @author xuk
 * @version 1.0
 * @since 2019-01-31
 */
@Controller
@RequestMapping("/system/dwDzz")
public class DwDzzController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(DwDzzController.class);

    @Autowired
    private DwDzzService dwDzzService;

    @RequestMapping("/page")
    public String forwordPage()  {
        return "system/dwDzz/dwDzzPage";
    }

    @TargetLogger("06010401")
    @RequiresPermissions("ROLE_XTGL")
    @RequestMapping( "/list")
    @ResponseBody
    public ResultDto queryDwDzzList(@RequestParam Map<?, ?> paramMap){
    	int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());
        try {
            ResultDto page = dwDzzService.queryListByPage(paramMap,pageNumber,pageSize);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }
    @TargetLogger("06010402")
    @RequiresPermissions("ROLE_XTGL")
    @RequestMapping("/excel")
    public void exportDwDzzList(HttpServletResponse response,@RequestParam Map<?, ?> paramMap){
        //导出默认1000行
        int pageSize = EXPORT_SIZE;
        int pageNumber = 1;
        OutputStream os = null;
        try {
            ResultDto page = dwDzzService.queryListByPage(paramMap,pageNumber,pageSize);
            List list = page.getRows();

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=exportDwDzz"+ System.currentTimeMillis() + ".xls");
            os = response.getOutputStream();

            ExportBeanExcel<DwDzz> export = new ExportBeanExcel<DwDzz>();
            //根据需求选择导出字段，注意数据库中带有_等字符字段修改
            //导出表头
            String[] headers = {"单位代码","单位名称","单位简称","调证年份","调证字号","录入单位","录入时间","修改单位","修改时间"};
            //对应字段 headers 与cols一一对应
            String[] cols = {"dwdm","dwmc","dwjc","dzyear","dzz","lrdwmc","rksj","xgdwmc","xgsj"};
			
            export.exportExcel("单位调证字号",headers,cols,list,os);

            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @RequestMapping("/checkDwDzz")
    @ResponseBody
    public String checkDwDzz(String dwdm) {
        DwDzz dwDzz = new DwDzz();

        if (StringUtils.isNotBlank(dwdm)){
            dwDzz.setDwdm(dwdm);
        }else{
            UserInfo user = dwDzzService.getUserInfo();
            dwDzz.setDwdm(user.getJgdm());
        }

        try {
            dwDzz = dwDzzService.queryAsObject(dwDzz);
            if (dwDzz!=null){
                return "true";
            }else{
                return "false";
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("060101")
    @RequiresPermissions("ROLE_XTGL")
    @RequestMapping("/curd")
    @ResponseBody
    public Map<String,String> curd(String curdType,DwDzz dwDzz) throws Exception {
    	Map<String,String> resultMap = new HashMap<>();
    	String msg = null;
        if (dwDzz!=null){
        	if (StringUtils.equalsIgnoreCase(curdType,"insert")){
        		//valid校验需在DwDzz的字段上增加校验规则，规则与表单规则保持一致
        		msg = ValidateUtil.valid(dwDzz);
        		if (StringUtils.isNotBlank(msg)){
        			logger.error("valid insert DwDzz is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                DwDzz dwDzz1 = dwDzzService.queryDwDzzByDwdm(dwDzzService.getUserInfo().getJgdm());
                if (dwDzz1!=null){
                    logger.error("该单位已存在调证字，请勿重复录入。"+dwDzzService.getUserInfo().getJgdm());
                    resultMap.put("msg","该单位已存在调证字，请勿重复录入。");
                    return resultMap;
                }
                 dwDzzService.insert(dwDzz);
            }else if (StringUtils.equalsIgnoreCase(curdType,"delete")){
            	if(StringUtils.isNotBlank(dwDzz.getPk())) {
                    dwDzzService.delete(dwDzz.getPk()); //主键删除
                }else {
                    msg="没有要删除的数据";
                    logger.error("valid delete DwDzz is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
            }else if (StringUtils.equalsIgnoreCase(curdType,"update")){
            	msg = ValidateUtil.valid(dwDzz);
        		if (StringUtils.isNotBlank(msg)){
        			 logger.error("valid update DwDzz is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                dwDzzService.updateByPrimaryKey(dwDzz);
            }
            msg = "操作成功";
        }else{
            msg="信息未填写";
            logger.error(msg);
        }
    	resultMap.put("msg",msg);
        return resultMap;
    }
    
}
